<template>
  <div class="License">
    <div class="page-head">
      <div class="page-bread">
        <div class="bread-prev" @click="back">
          应用管理
        </div>
        <div class="bread-divider">
          /
        </div>
        <div class="bread-now">
          类别管理
        </div>
      </div>
      <div class="page-tool">
        <div class="tool-btn" @click="open('add')">新增类别</div>
      </div>
      
    </div>
    <div class="page-body">
      <div class="table_data">
        <el-scrollbar class="scroll-bar">
          <el-table :data="tableData" stripe :fit="true">
            <el-table-column
              :show-overflow-tooltip="true"
              prop="name"
              label="类别名称"
            >
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              prop="remark"
              label="备注"
            >
            </el-table-column>
            <el-table-column label="操作" width="160" align="center">
              <template slot-scope="{row}">
                <div class="operation-col">
                  <div class="txt-btn primary"  :class="{'grey notAllow': row.group_type === 0}" @click="open('edit', row)">修改</div>
                  <el-divider direction="vertical"></el-divider>
                  <div class="txt-btn primary"  :class="{'grey notAllow': row.group_type === 0}" @click="doDelete(row)">删除</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div class="page-footer">
        <pagina-tion
          class="page-pager"
          v-show="total>=0"
          :background="true"
          :total="total"
          :offset.sync="offset"
          :limit.sync="limit"
          @pagination="getChangePage"
        />
       <button class="page-button">确定</button>
      </div>
    </div>
    <!-- 新增和修改弹框 -->
    <el-dialog :visible.sync="model.visible" width="450px" :title="model.type==='add'?'新增类别':'修改类别'" :close-on-click-modal="false" :show-close="false">
      <div class="dialog-body">
        <el-form ref="form" :model="form" label-width="120px" label-position="left">
          <el-form-item label="类别名称" class="required">
            <el-input
              placeholder="请输入类别名称"
              :maxlength="6"
              v-model="form.name"
              name="cateName"
              v-validate="'required'"
            />
            <div v-show="errors.has('cateName')" class="el-form-item__error">{{ errors.first('cateName') }}</div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model.trim="form.remark"
              maxlength="128"
            />
          </el-form-item>
          <el-form-item label="应用主图标" class="required">
            <el-upload
              name="cover_url"
              v-model="form.cover_url"
              v-validate="'required'"
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadReq"
              :accept="imgAccept"  
            >
              <img v-if="form.cover_url" key="pic" :src="form.cover_url" class="upload-img">
              <img v-else key="default" src="~assets/img/upload.png" class="upload-img">
            </el-upload>
            <div v-show="errors.has('cover_url')" class="el-form-item__error">{{ errors.first('cover_url') }}</div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit(model.type)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="stopVisable" width="450px" title="终止 License" :close-on-click-modal="false" :show-close="false">
      <div class="dialog-body">
        <el-form ref="form" :model="form" label-width="90px" label-position="left">
          <el-form-item label="终止原因">
            <el-input
              type="textarea"
              placeholder="请输入终止原因"
            />
          </el-form-item>
          
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="stopVisable = false">取消</el-button>
        <el-button type="primary" @click="submit(model.type)">终止续约</el-button>
      </span>
    </el-dialog>

      <!-- 删除弹窗 -->
    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico"
             src="~assets/img/warning.png">
        <div class="comfirm-txt">
          <div>
            确定删除该条数据？
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="cateDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import { limit, imgAccept } from '@/consts/consts'
import * as api from '@/api'
import { appGroupFormKey } from '@/consts/formKey'
import client from '@/utils/oss'

export default {
  data() {
    return {
      imgAccept,
      limit,
      total: 0,
      offset: 0,
      tableData: [],
      model: {
        type: 'add',
        visible: false
      },
      stopVisable: false,
      form: {
        ...appGroupFormKey
      },
      app_id:'',
      uploadFile: null,
      visibility: false,
      loading: null
    }
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    close() {
      this.model.visible = false
      this.form = {...appGroupFormKey}
    },

    open(type, row=null) {
      this.$validator.reset()
      this.model.type = type
      if (row) {
        if(row.group_type === 0){
          return false
        }
        for (const k in appGroupFormKey) {
          this.form[k] = row[k]
        }
        this.app_gid = row.app_gid
      }
      this.model.visible = true
    },
    getChangePage(val) {
      this.offset = val.offset
      this.getList()
    },

    beforeAvatarUpload(file) {
      const typeOk = ['image/png', 'image/PNG', 'image/jpg', 'image/JPG', 'image/jpeg', 'image/JPEG'].includes(file.type)
      if (typeOk) {
        this.uploadFile = file;
        return true;
      } else {
        return this.$message.warning('只支持png、jpg格式的图片')
      }
    },

    submit() {
      this.$validator.validateAll().then(valid => {
        if (valid) {
          this.addOrEdit()
        } else {
          this.$message.warning('有信息未填写正确')
        }
      })
    },

    doDelete(row) { 
      if(row.group_type === 0){
        return false
      }
      this.app_id = row.app_gid
      this.visibility = true
    },
    cateDelete(){
      this.appGroupDelete()

    },
    // 应用分组
    async getList() {
      const { code, data } = await api.category(this).appGroupList({
        offset: this.offset,
        limit:  this.limit
      })
      if (code === 0) {
        this.tableData = data
      }
    },  
    async addOrEdit() {
      let fn = this.model.type === 'add' ? 'appGroupAdd' : 'appGroupUpdate'
      const { code } = await api.category(this)[fn](this.form, this.app_gid)
      if (code === 0) {
        this.form.name = ''
        this.form.remark = ''
        this.form.cover_url = ''
        this.$message.success('操作成功')
        this.close()
        this.getList()
      }
    },
    async uploadReq() {
      let [n, suf] = this.uploadFile.name.split('.')
      let fileName = `${n}_${+new Date}.${suf}`
      this.loading = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let result = await client.put(`app/${fileName}`, this.uploadFile)

      if (result) {
        console.log('oss返回: ', result.res.requestUrls[0])
        this.form.cover_url = result.res.requestUrls[0]
        this.loading.close()
      }
    },

    async appGroupDelete() {
      const { code, data } = await api.category(this).appGroupDelete(this.app_id)
      if (code === 0) {
        this.$message.success('操作成功')
        this.program_id = ''
        this.visibility = false
        if (this.total % this.limit === 1) {
          if (this.offset >= this.limit) {
            this.offset -= this.limit
          }
        }
        this.getList()
      }
    },
  },
  created(){
    this.getList()
  },
}
</script>

<style lang="stylus">
.Type {

}
</style>